<template>
  <q-page padding>
    <q-card flat bordered>
      <q-card-section class="row items-center justify-between">
        <div class="row items-center">
          <q-btn
            icon="arrow_back"
            flat
            round
            dense
            class="q-mr-sm"
            @click="handleCancel"
          />
          <div class="text-h6">{{ isEdit ? '编辑展会信息' : '新增展会信息' }}</div>
        </div>
        <q-btn
          v-if="isEdit"
          :label="isEditing ? '取消编辑' : '编辑'"
          :color="isEditing ? 'grey' : 'primary'"
          @click="toggleEdit"
        />
      </q-card-section>

      <q-card-section class="bg-blue-1 q-mb-md">
        <div class="row items-center no-wrap">
          <q-icon name="info" color="info" size="24px" class="q-mr-sm"/>
          <div>
            <div class="text-subtitle1 text-weight-medium">AI智能辅助创建</div>
            <div class="text-body2">
              您可以仅填写部分关键信息（必须包含可访问的官网地址），系统将通过AI自动补全其他展会信息。
              填写完成后点击"确认创建"，我们的AI模型将处理并完善展会数据。
            </div>
          </div>
        </div>
      </q-card-section>

      <q-card-section>
        <q-form @submit="handleSubmit" ref="formRef">
          <div class="row q-col-gutter-md custom-disabled">
            <div class="col-12 col-md-6">
              <!-- <q-input
                v-model="formData.exhibition_number"
                label="展览会编号"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入展览会编号',
                  val => /^\d{2,6}$/.test(val) || '展览会编号必须是2-6位数字'
                ]"
              /> -->
              <q-input
                v-model="formData.exhibition_number"
                label="展览会编号"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
            </div>

            <div class="col-12 col-md-6">
              <!-- <q-input
                v-model="formData.chinese_name"
                label="中文名称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入中文名称',
                  val => /^[\u4e00-\u9fa5A-Z、]+$/.test(val) || '中文名称只能包含汉字、英文大写字母和顿号',
                  val => val.startsWith(formData.country) || `展会名称必须以国别（${formData.country}）开头`
                ]"
              /> -->
              <q-input
                v-model="formData.chinese_name"
                label="中文名称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入中文名称'
                  ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.english_name"
                label="英文全称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- <q-input
                v-model="formData.english_name"
                label="英文全称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入英文全称',
                  val => /^[0-9A-ZÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ. +\-\'()（）&,:]+$/.test(val) || '英文全称只能包含大写字母、数字、点、空格、连字符、括号、逗号、冒号和&符号'
                ]"
              /> -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.english_short_name"
                label="英文简称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
    
              />
              <!-- <q-input
                v-model="formData.english_short_name"
                label="英文简称"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^[0-9A-Z. +\-]+$/.test(val) || '英文简称只能包含大写字母、数字、点、空格和连字符',
                  val => !val || val !== formData.english_name || '英文简称不能与全称相同'
                ]"
              /> -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.holding_time"
                label="举办时间"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- <q-input
                v-model="formData.holding_time"
                label="举办时间"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入举办时间',
                  val => /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/.test(val) || '举办时间格式必须为：数字月数字日-数字月数字日'
                ]"
              /> -->
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.continent"
                :options="['亚洲', '欧洲', '非洲', '北美洲', '南美洲', '大洋洲']"
                placeholder="若未填写AI系统将自动创建"
                label="洲"
              />
              <!-- :disable="formFields.disabled" -->
              <!-- :rules="[val => !!val || '请选择洲']" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.country"
                label="国别"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
                <!-- :rules="[val => !!val || '请输入国别']" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.city"
                label="城市"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
                <!-- :rules="[val => !!val || '请输入城市']" -->

            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.frequency"
                placeholder="若未填写AI系统将自动创建"
                :options="['一年一届', '一年两届', '一年四届', '两年一届', '三年一届', '四年一届']"
                label="举办频率"
                :disable="formFields.disabled"
              />
              <!-- :rules="[val => !!val || '请选择举办频率']" -->
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.industry"
                :options="industryTypes"
                placeholder="若未填写AI系统将自动创建"
                label="行业"
                :disable="formFields.disabled"
              />
              <!-- :rules="[val => !!val || '请选择行业']" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.organizer"
                label="主办方"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- :rules="[
                  val => !val || /^[\u4e00-\u9fa5A-Za-zÄÖÜäöüßéèêëàâôûùÿç&.、 ()]+$/.test(val) || '主办方名称只能包含汉字、大小写字母、德语字母和顿号'
                ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.organizer_en"
                label="主办方英文"
                :disable="formFields.disabled"
              />
              <!-- :rules="[
                  val => !val || /^[a-zA-Z&.,/ ()ÄÖÜäöüßéèêëàâôûùÿç\-']+$/.test(val) || '主办方英文名称格式不正确'
                ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.contact_info"
                label="联系方式"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- :rules="[
                  val => !!val || '请输入联系方式',
                  val => /^[0-9A-Za-z\s\-\+\(\)\.,]+$/.test(val) || '联系方式格式不正确'
                ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.exhibition_hall"
                label="展馆"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- :rules="[
                    val => !!val || '请输入展馆',
                    val => val.startsWith(formData.city) || `展馆名称必须以城市名（${formData.city}）开头`
                  ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.exhibition_hall_english"
                label="展馆英文"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
              />
              <!-- :rules="[
                  val => !!val || '请输入展馆英文名称',
                  val => /^[A-Za-z\-'ÄÖÜäöüßéèêëàâôûùÿç&., ]+$/.test(val) || '展馆英文名称格式不正确'
                ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.official_website"
                label="官网"
                placeholder="该字段必须填写"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '该字段必须填写',
                ]"
              />
              <!-- val => !val || /^(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]+(?:\/[a-zA-Z0-9-_/]*)?(?:\.[a-z]+)?$/.test(val) || '官网格式不正确' -->
            </div>

            <div class="col-12">
              <q-input
                v-model="formData.exhibit_scope"
                type="textarea"
                label="展品范围"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                autogrow
              />
              <!-- :rules="[
                  val => !!val || '请输入展品范围',
                  val => val?.length <= 100 || '展品范围不能超过100字',
                  val => !val?.endsWith('。') || '展品范围不能以句号结尾',
                  val => val === val?.trim() || '展品范围不能有前后空格'
                ]" -->
            </div>

            <div class="col-12">
              <q-input
                v-model="formData.description"
                type="textarea"
                label="简介"
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                autogrow
              />
              <!-- :rules="[
                  val => !val || val?.length <= 150 || '简介不能超过150字',
                  val => !val?.endsWith('。') || '简介不能以句号结尾',
                  val => !val || val === val?.trim() || '简介不能有前后空格'
                ]" -->
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.ufi_certified"
                :options="ufiOptions"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                placeholder="若未填写AI系统将自动创建"
                label="是否UFI认证"
                :disable="formFields.disabled"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model.number="formData.exhibition_area"
                type="number"
                label="展会面积" 
                placeholder="若未填写AI系统将自动创建"
                :disable="formFields.disabled"
                suffix="㎡"
              />
            </div>
          </div>

          <div class="row q-mt-md justify-end">
            <q-btn
              label="取消"
              color="grey"
              flat
              class="q-mr-sm"
              @click="confirmCancel"
              v-if="!isEdit || isEditing"
            />
            <q-btn
              label="确认创建"
              color="primary"
              type="submit"
              v-if="!isEdit || isEditing"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useQuasar } from 'quasar'
import { getExhibition, createExhibition, updateExhibition } from 'src/api/exhibition'

const $q = useQuasar()
const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEdit = ref(false)

const ufiOptions = [
  { label: '未知', value: 0 },
  { label: '是', value: 1 },
  { label: '否', value: 2 }
]

// 修改 formData 中的初始值
const formData = ref({
  exhibition_number: '新增',
  chinese_name: '',
  english_name: '',
  english_short_name: '',
  holding_time: '',
  event_date_end: '',
  event_date_start:'',
  continent: '',
  country: '',
  city: '',
  frequency: '',
  industry: '',
  organizer: '',
  organizer_en: '',
  contact_info: '',
  exhibition_hall: '',
  exhibition_hall_english: '',
  official_website: '',
  exhibit_scope: '',
  description: '',
  ufi_certified: 0,  // 设置默认值为 0（未知）
  exhibition_area: null
})

const industryTypes = [
  "农林牧渔",
  "食品饮料",
  "纺织服饰",
  "皮革鞋包",
  "妇婴用品",
  "美容美发",
  "礼品玩具及宠物用品",
  "钟表眼镜",
  "珠宝首饰",
  "生活用品",
  "婚庆用品",
  "酒店用品",
  "办公用品",
  "教育装备",
  "劳保用品",
  "文体娱乐",
  "健康养老",
  "医疗及制药设备",
  "药品及原料",
  "汽车",
  "自行车电动车摩托车",
  "航空航天",
  "船舶和轨道等交通",
  "光电产品",
  "计算机通信及电子设备",
  "仪表仪器",
  "冷暖设备",
  "泵阀管道",
  "五金工具",
  "工业机械",
  "工程机械",
  "农业机械",
  "食品加工设备",
  "采矿及设备",
  "电力及新能源设备",
  "节能环保",
  "化工产品",
  "高新材料 / 技术",
  "其他设备 / 材料",
  "家电",
  "家具家居",
  "建筑建材",
  "物流仓储",
  "电商和交易会",
  "广告传播",
  "印刷包装",
  "公共安全",
  "连锁加盟",
  "综合类",
  "其他"
]

// 修改 getExhibitionDetail 函数
const getExhibitionDetail = async (id) => {
  try {
    const res = await getExhibition(id)
    const data = { ...res.data }
    // 确保 ufi_certified 是数字类型
    data.ufi_certified = Number(data.ufi_certified || 0)
    Object.assign(formData.value, data)
  } catch (error) {
    console.error(error)
    $q.notify({
      type: 'negative',
      message: '获取展会信息失败'
    })
  }
}

const isEditing = ref(false)

// 修改所有输入组件，添加 :disable 属性
const formFields = computed(() => {
  const disabled = isEdit.value && !isEditing.value
  return {
    disabled,
    // 可以添加其他通用属性
  }
})

// 添加切换编辑状态的方法
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 修改 handleSubmit
const handleSubmit = async () => {
  try {
    const submitData = { ...formData.value }

    if (isEdit.value) {
      await updateExhibition(route.query.id, submitData)
      $q.notify({
        type: 'positive',
        message: '更新成功'
      })
      isEditing.value = false  // 保存成功后退出编辑状态
    } else {
      await createExhibition(submitData)
      $q.notify({
        type: 'positive',
        message: '创建成功'
      })
    }

    router.push('/exhibition')
  } catch (error) {
    console.log(error)
    $q.notify({
      type: 'negative',
      message: '保存失败'
    })
  }
}

// 修改 confirmCancel
const confirmCancel = () => {
  const message = isEdit.value ?
    (isEditing.value ? '确定要取消编辑吗？未保存的内容将会丢失' : '确定要返回列表页吗？') :
    '确定要取消编辑吗？未保存的内容将会丢失'

  $q.dialog({
    title: '确认提示',
    message,
    persistent: true,
    ok: {
      label: '确定',
      color: 'primary'
    },
    cancel: {
      label: '取消',
      color: 'grey'
    }
  }).onOk(() => {
    if (isEdit.value && isEditing.value) {
      isEditing.value = false
      getExhibitionDetail(route.query.id)  // 重新加载数据
    } else {
      handleCancel()
    }
  })
}

const handleCancel = () => {
  router.push('/exhibition')
}

onMounted(() => {
  const id = route.query.id
  if (id) {
    isEdit.value = true
    getExhibitionDetail(id)
  }
})

// 添加计算属性：根据开始和结束时间生成 holding_time
const computedHoldingTime = computed(() => {
  if (!formData.value.event_date_start || !formData.value.event_date_end) {
    return ''
  }

  const startDate = new Date(formData.value.event_date_start)
  const endDate = new Date(formData.value.event_date_end)

  return `${startDate.getMonth() + 1}月${startDate.getDate()}日-${endDate.getMonth() + 1}月${endDate.getDate()}日`
})

// 监听计算属性的变化，更新 holding_time
watch(computedHoldingTime, (newValue) => {
  formData.value.holding_time = newValue
})

// 监听 holding_time 的变化，更新开始和结束时间
watch(() => formData.value.holding_time, (newValue) => {
  if (!newValue) return

  const match = newValue.match(/^(\d+)月(\d+)日-(\d+)月(\d+)日$/)
  if (match) {
    const [_, startMonth, startDay, endMonth, endDay] = match
    const currentYear = new Date().getFullYear()

    formData.value.event_date_start = `${currentYear}-${String(startMonth).padStart(2, '0')}-${String(startDay).padStart(2, '0')} 00:00:00`
    formData.value.event_date_end = `${currentYear}-${String(endMonth).padStart(2, '0')}-${String(endDay).padStart(2, '0')} 00:00:00`
  }
})
</script>

<style>
.q-field--disabled {
  cursor: default !important;
  opacity: 1 !important;
}
.q-field--disabled * {
  cursor: default !important;
  color: rgba(0, 0, 0, 0.9) !important;
}
.q-field--disabled .q-field__label {
  color: rgba(0, 0, 0, 0.6) !important;
}
</style>
